﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;
using ImageAppViewModels;
using BrainTechLLC.WPF;
using BrainTechLLC;

namespace WpfImageDuplicates
{
    /// <summary>
    /// Interaction logic for ThumbViewDebug.xaml
    /// </summary>
    public partial class ThumbViewDebug : UserControl
    {
        SimpleDispatcherTimer _timer;

        public static readonly DependencyProperty FileImageViewModelProperty =
            DependencyProperty.Register("FileImageViewModel", typeof(FileImageViewModel), typeof(ThumbViewDebug), new PropertyMetadata(null, OnFileImageViewModelPropertyChanged));

        public FileImageViewModel FileImageViewModel
        {
            get { return (FileImageViewModel)GetValue(FileImageViewModelProperty); }
            set { SetValue(FileImageViewModelProperty, value); }
        }

        private static void OnFileImageViewModelPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ThumbViewDebug source = d as ThumbViewDebug;
            source.UpdateFileImageViewModel(e.OldValue as FileImageViewModel, e.NewValue as FileImageViewModel);
        }

        private void UpdateFileImageViewModel(FileImageViewModel viewModelOld, FileImageViewModel viewModelNew)
        {
            if (viewModelNew != viewModelOld)
            {
                FileImageViewModel = viewModelNew;

                if (viewModelOld != null)
                {
                }

                // Let the UI bind to the view-model.
                this.DataContext = FileImageViewModel;
                stacker.DataContext = FileImageViewModel;
            }
        }

        public ThumbViewDebug()
        {
            InitializeComponent();
            _timer = new SimpleDispatcherTimer(1000, timer=>Timer_Tick(timer));            
            _timer.Start();
        }

        RunInitializationResult Timer_Tick(SimpleDispatcherTimer timer)
        {
            chkThumb.IsChecked = FileImageViewModel.Item.ThumbnailCached != null;
            chkBitmap.IsChecked = FileImageViewModel.BitmapLoaded;
            chkThumbVis.IsChecked = FileImageViewModel.ThumbVisible;
            chkThumbSourceCached.IsChecked = FileImageViewModel.ThumbImageSourceCached != null;
            chkImageBytes.IsChecked = FileImageViewModel.Item.ImageBytesCached != null && FileImageViewModel.Item.ImageBytesCached.Length > 0;
            chkDirty.IsChecked = FileImageViewModel.Dirty;
            desiredOrdering.Text = FileImageViewModel.DesiredOrdering.ToString();
            
            return RunInitializationResult.DidSomething;
        }
    }
}
